package com.itheima.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exception.UserException;
import com.itheima.pojo.User;
import com.itheima.service.UserService;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping("/getUserName")
    public Result getUserName(){
        //Principal 主体 ，就是当前登录的人
        org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User)
                        SecurityContextHolder.getContext().getAuthentication().getPrincipal();


        return Result.OK("",user.getUsername());
    }

    @RequestMapping(("/add"))
    public Result add(@RequestBody User user) {
        try {
            userService.add(user);
            return new Result(true, "用户添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "用户添加失败！");
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return userService.findPage(queryPageBean);
    }

    @RequestMapping(("/findById4Edit"))
    public Result findById4Edit(Integer id) {
        //使用map集合接收,用户信息、角色信息、用户勾选的id
        Map map = userService.findById4Edit(id);
        return new Result(true, "", map);
    }


    @RequestMapping("/edit")
    public Result edit(@RequestBody User user) {
        try {
            userService.edit(user);
            return new Result(true, "用户更新成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "用户更新失败！");
        }
    }

    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            userService.delete(id);
        } catch (UserException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "用户删除失败！");
        }
        return new Result(true, "用户删除成功！");
    }


}
